<?php
class MW_Helpdesk_Model_Email
{
    private $_mailGateway = array();
    private $_mailNoDelGateway = array();
	private $_inbox = array();
	

	
	private function _contentDecoder($part)
	{
		$content = $part->getContent();
		if($part->headerExists('content-transfer-encoding')){
			switch ($part->contentTransferEncoding) {
				case 'quoted-printable':
					$content = quoted_printable_decode($content);
				break;
				case 'base64':
					$content = base64_decode($content);
				break;
			}
		}
		return $content;
	}

	/**
	 * reply mail get info mail from Email, deliver mail for customer or member
	 * 
	 * @param string $to
	 * @param string $template
	 * @param array $data
	 * @return void
	 */
   	public function sentMail($from, $to, $templateId, $dataInbox)
   	{
   		//echo '<pre>';var_dump($dataInbox);die(); 
   		
		$storeId = Mage::app()->getStore()->getId();  
		//$templateIds = Mage::getStoreConfig($template,$storeId); 
		//echo $templateIds;die();
		
   		// $sender can set identity of diffrent Store emails
		// found in "System->Configuration->General->Store Email Addresses"
		$sender = array ('name'  => $from,
						 'email' => $from);
   		
		$translate  = Mage::getSingleton('core/translate');
		$translate->setTranslateInline(false);
		  
		try{
			$emailTemplate = Mage::getModel('core/email_template');

			// cac du lieu co the thiet lap trong file template gom
			$data = array();
			$data['subject'] = $dataInbox['subject'];
			$data['message'] = nl2br($dataInbox['message']);
			$data['store_name'] = Mage::app()->getStore()->getName();
			$data['department_name'] = $dataInbox['department_name'];
			
			if(isset($dataInbox['operator_name'])) {
				$data['operator_name'] = nl2br($dataInbox['operator_name']);
			}
			if(isset($dataInbox['customer_name'])) {
				$data['customer_name'] = nl2br($dataInbox['customer_name']);
			}
			if(isset($dataInbox['operator_direct_link'])) {
				$data['operator_direct_link'] = $dataInbox['operator_direct_link'];
			}
			if(isset($dataInbox['customer_direct_link'])) {
				$data['customer_direct_link'] = $dataInbox['customer_direct_link'];
			}
			if(isset($dataInbox['expired_time'])) {
				$data['expired_time'] = $dataInbox['expired_time'];
			}
			if(isset($dataInbox['late'])) {
				$data['late'] = $dataInbox['late'];
			}
			if(isset($dataInbox['staff_name'])) {
				$data['staff_name'] = $dataInbox['staff_name'];
			}
			
			if(isset($dataInbox['note'])) {
				$data['note'] = $dataInbox['note'];
			}
			
			if(isset($dataInbox['file_attachment']) && $dataInbox['file_attachment'] !=''){
				$file_attachments = explode(";", $dataInbox['file_attachment']);
				foreach ($file_attachments as $file_attachment) {
					$mail = $emailTemplate->getMail();
					$fileContents  = 
						file_get_contents(Mage::getBaseDir('media') . DS . 'ticket' . DS . $file_attachment);
					$file = $mail->createAttachment($fileContents);
					$file->filename = $file_attachment;
					//$file->type = 'application/zip';
				}
			}
			
//			Zend_Debug::dump($data);
//			echo $templateId. '<br />';
//			echo $sender. '<br />';
//			echo $to;
//			die();
			$emailTemplate->sendTransactional(
				$templateId, 
			    $sender,
			    $to,
			    null,	// name sender, not describle
			    $data, 
			    $storeId
			);
			$translate->setTranslateInline(true);
		} catch(Exception $e) {
		 	echo "email not send";die();	
		}
   	}	
   	
	public function processGetMail()
	{
   		
   		$flag = false; // have got email
   		foreach ($this->_mailGateway as $mail) {
   			if ($mail->countMessages() > 0) {
   				$keepAlive = 0; 
   				$flag = true;
   				for ($n = $mail->countMessages(); $n > 0; $n--) {
   					try {
	   					$message = $mail->getMessage($n);
	   					
	   					$date = date("Y-m-d h:i:s", Mage::getSingleton('core/date')->timestamp($message->date)); 
						$from = $this->_fromDecoder($message->from);
						
//////////////////////////////?						
						if(Mage::getStoreConfig('helpdesk/config/reply_to')) {
							if(isset($message->replyTo)) {
								$from = $message->replyTo;
							}
						}
						try {
							$subject = $this->_subjectDecoder($message->subject);
						} catch(Exception $e) {
							Mage::log($subject);
						}
						$to           		= $this->_toDecoder($message->envelopeTo);
						$plainContent 		= null;
						$htmlContent  		= null;
						$file_attachment  	= '';
						$file_attachments  	= '';
						$name        		= $this->_nameDecoder($message->from);
						
						if ($message->isMultipart()) {
							$files  = array();
							foreach (new RecursiveIteratorIterator($message) as $part) {
								switch (strtok($part->contentType, ';')) {
									case 'text/plain':
										$plainContent = $this->_contentDecoder($part);
									break;
									case 'text/html':
										$htmlContent = $this->_contentDecoder($part);
									break;
									default: //attachment handle
										$file_attachment = $part->getHeader('content-disposition');
		                                $file_attachment = explode("=",$file_attachment);
		                                $file_attachment = str_replace('"',"",$file_attachment[1]);
										// upload the attachment
										$content = $this->_contentDecoder($part); // get content
										$path = Mage::getBaseDir('media') . DS . 'ticket' . DS . $file_attachment;
										$fh = fopen($path, 'w');
										fwrite($fh, $content);
										fclose($fh);
										//multi file attachment
										$files[] = $file_attachment;
									break;
								}
							}
							$file_attachments = implode(';', $files);
						} else {
							$plainContent = $message->getContent();
						}
						
						$this->_inbox[] = array('created_time'		=> $date,
												'name'				=> $name,
												'sender'			=> $from,
												'to'				=> $to,
												'subject'			=> $subject,
												'content'			=> $plainContent,
												'file_attachment'	=> $file_attachments);	
	   					// keep alive
						if ($keepAlive % 5 == 0) $mail->noop();
						$keepAlive ++;	
   					} catch(Exception $e) {
						Mage::log($message);
					}
   				}

   				// delete mail
				for ($i = count($mail); $i; --$i) {
		    		$mail->removeMessage($i);
				}		
   			}
   		}
   		
   		// call save ticket if exist email
   		if($flag) {
   			$this->saveTicket($flag);
   		}
   		return $flag;
	}
	
	public function saveTicket()
	{
		foreach ($this->_inbox as $dataInbox) {
			// cat lay phan tren =========
		    $content = explode("=========", $dataInbox['content']);
    		if(sizeof($content) != 1) {
    			$dataInbox['content'] = $content[0];
    		}
			$sub = explode(" - ", $dataInbox['subject']);
			if(sizeof($sub) >= 2) {
				//save to history
				$dataInbox['sub'] = $sub[0];
				Mage::getModel('helpdesk/history')->saveHistoryFromGateway($dataInbox);	
			} else {
				// neu cho phep tao moi ticket tu mail
				if(Mage::getStoreConfig('helpdesk/config/creticket_email')) {
					Mage::getModel('helpdesk/ticket')->saveTicketFromGateway($dataInbox);
				}
			}
		}
	}
	
	public function runCron()
	{
		$flag = $this->processGetMail();
		$this->generateNotice();
		return $flag;
	}
	
	// generate notify
	public function generateNotice() {
		$now = time();	// Time via server, no depend of Timezone setup by Magento
		$noticeTime = (int) Mage::getStoreConfig('helpdesk/config/notice');
		$completeTime = (int) Mage::getStoreConfig('helpdesk/config/complete'); 
		$stepNoticeTime = (int) Mage::getStoreConfig('helpdesk/config/step_notice');
        $noticeTime = $noticeTime*60*60;
		$stepNoticeTime = $stepNoticeTime*60*60;
		$completeTime = $completeTime*60*60;
		
		$collection =  Mage::getResourceModel('helpdesk/ticket_collection')
            ->addFieldToFilter('status', array('neq'=>MW_HelpDesk_Model_Config_Source_Status::STATUS_CLOSED));
            
        foreach ($collection as $ticket) {
        	$lastReplyTime = strtotime($ticket->getLastReplyTime());
         	$diff = $now - $lastReplyTime;
         	
	        $stepReplyTime = strtotime($ticket->getStepReplyTime());
	        $diff2 = $now - $stepReplyTime;

         	// customer reply => sent mail for member
         	
	        // Dam bao ngay nghi la ko dua notify 
	        $weekends = Mage::getStoreConfig('helpdesk/config/weekend');
			$weekend = explode(',',$weekends);
			$today = date('l', time());

         	if($ticket->getStatus() == MW_HelpDesk_Model_Config_Source_Status::STATUS_OPEN && in_array($today, $weekend)) {
	         	if(($noticeTime > 0 && $diff > $noticeTime && $lastReplyTime > $stepReplyTime) 
	         	|| ($stepNoticeTime > 0 && $diff2 > $stepNoticeTime && $lastReplyTime < $stepReplyTime)) {	 		
	         		// if department enable sent mail notice for member
	         		$department = Mage::getModel('helpdesk/department')->load($ticket->getDepartmentId());
	         	    if($department->getAutoNotification() == 1) {
		          		if($ticket->getMemberId() != 0) {
		          			$members = Mage::getResourceModel('helpdesk/member_collection')
								->addFieldToFilter('member_id', array('eq' => $ticket->getMemberId()));
							foreach ($members as $member) {
								// Sent ticket if not solved
								$mailData = array();
								$to = $member->getEmail();
								$mailData['operator_name'] = $member->getName();
								$mailData['customer_name'] = $ticket->getName();
								$mailData['subject'] = $ticket->getCodeId() . ' - ' . $ticket->getSubject();
								$mailData['message'] = $ticket->getContent();
								$diff = $diff/60/60;
								$mailData['late'] = round($diff);
								
								//get last email(history) sent if exist
								$historyCollection = Mage::getModel('helpdesk/history')->getCollection()
									 ->addFilter('ticket_id', $ticket->getId())
									 ->setOrder('history_id', 'DESC');
								if($historyCollection->getSize()>0) {
									foreach($historyCollection as $history) {
										$mailData['message'] = $history->getContent();break;
									}
								}
								
								$mailData['operator_direct_link'] = Mage::getBaseUrl() . 'helpdesk/viewticket/moderator/code/' . $ticket->getCodeMember();
								
						   		$gateway = Mage::getModel('helpdesk/gateway')->load($department->getDefaultGateway());
						   		$from = $gateway->getEmail();	// email tuong ung
						   		$mailData['department_name'] = $department->getName();
								$templateId = $department->getLateReplyTicketOperator();
							  	if($templateId == '') {
						   			$storeId = Mage::app()->getStore()->getId();  
						   			$template = 'helpdesk/config/late_reply_ticket_operator';
									$templateId = Mage::getStoreConfig($template,$storeId); 
						   		}
								
								$this->sentMail($from, $to, $templateId, $mailData);
								
								$ticket = Mage::getModel('helpdesk/ticket')->load($ticket->getId());
	         					$ticket->setStepReplyTime(now())->save();
				   			}	
		          		}
		        	}
	         	}
         	} 
         	
         	// member reply => close ticket
         	if($ticket->getStatus() == MW_HelpDesk_Model_Config_Source_Status::STATUS_PROCESSING){
	         	if( $diff > $completeTime ){
	         	//if( $diff > ($completeTime * 60) ){
	         		// change status STATUS_COMPLETE
	         		$ticket = Mage::getModel('helpdesk/ticket')->load($ticket->getId());
	         		$ticket->setStatus(MW_HelpDesk_Model_Config_Source_Status::STATUS_CLOSED)->save();
	         	}
         	}
        }  	
	}
}